package com.example.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ServiceDiscoveryService {

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 获取所有服务名称
     */
    public List<String> getAllServices() {
        return discoveryClient.getServices();
    }

    /**
     * 根据服务名获取所有实例
     */
    public List<ServiceInstance> getServiceInstances(String serviceName) {
        return discoveryClient.getInstances(serviceName);
    }

    /**
     * 获取服务实例的详细信息
     */
    public List<Map<String, Object>> getServiceInstancesDetail(String serviceName) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        return instances.stream().map(instance -> {
            Map<String, Object> info = new HashMap<>();
            info.put("serviceId", instance.getServiceId());
            info.put("instanceId", instance.getInstanceId());
            info.put("host", instance.getHost());
            info.put("port", instance.getPort());
            info.put("uri", instance.getUri());
            info.put("scheme", instance.getScheme());
            info.put("metadata", instance.getMetadata());
            info.put("isSecure", instance.isSecure());
            return info;
        }).collect(Collectors.toList());
    }

    /**
     * 检查服务是否可用
     */
    public boolean isServiceAvailable(String serviceName) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        return instances != null && !instances.isEmpty();
    }

    /**
     * 获取服务的实例数量
     */
    public int getServiceInstanceCount(String serviceName) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        return instances != null ? instances.size() : 0;
    }
}
